package com.boyicloud.exchangeserver.netty.handler

import com.boyicloud.exchangeserver.common.DataBase
import com.boyicloud.exchangeserver.common.IdGenerator
import com.boyicloud.exchangeserver.domain.ClientInfo
import com.boyicloud.exchangeserver.netty.listener.NettyServerListener
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import java.net.InetSocketAddress

@ChannelHandler.Sharable
class InitializeHandler(private val serverType: NettyServerListener.ServerType) : ChannelInboundHandlerAdapter() {

    override fun channelActive(ctx: ChannelHandlerContext) {
        super.channelActive(ctx)
        val remoteAddress = ctx.channel().remoteAddress() as InetSocketAddress
        val clientInfo = ClientInfo(
            IdGenerator.snowflake.nextId(),
            false,
            ctx.channel(),
            remoteAddress.hostString,
            remoteAddress.port,
            rxBytes = 0.0, txBytes = 0.0
        )
        when (serverType) {
            NettyServerListener.ServerType.SOFTWARE -> DataBase.softwareListMap[ctx.channel().id()] = clientInfo
            NettyServerListener.ServerType.EQUIPMENT -> {
                //只有当售后端连接后才接受设备端的连接
                if (DataBase.softwareListMap.isNotEmpty()) {
                    DataBase.equipmentListMap[ctx.channel().id()] = clientInfo
                } else {
                    ctx.channel().close()
                }
            }
        }
    }

    override fun channelInactive(ctx: ChannelHandlerContext) {
        super.channelInactive(ctx)

        val channel = DataBase.penetrateMap[ctx.channel().id()]
        channel?.let { DataBase.penetrateMap.remove(it.id()) }
        DataBase.penetrateMap.remove(ctx.channel().id())

        when (serverType) {
            NettyServerListener.ServerType.SOFTWARE -> {
                channel?.let {
                    val originalEquipment = DataBase.equipmentListMap[channel.id()]
                    originalEquipment?.remark = ""
                }
                DataBase.softwareListMap.remove(ctx.channel().id())
            }
            NettyServerListener.ServerType.EQUIPMENT -> DataBase.equipmentListMap.remove(ctx.channel().id())
        }
    }
}